package com.javalong.mir.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javalong.mir.common.util.WechatUtil;
import com.javalong.mir.constant.Constant;
import com.javalong.mir.dwz.vo.ResponseVO;
import com.javalong.mir.pojo.User;
import com.javalong.mir.service.UserService;

@Controller
@RequestMapping("login")
public class LoginController {
	@Autowired
	private UserService userService;
	/**
	 * 通过页面传递回来的code，调用微信授权接口，获取到用户信息
	 * 判断用户是否存在，不存在，则创建新用户，存session
	 * @param code
	 * @param session
	 * @return
	 */
	@RequestMapping("loginByCode")
	@ResponseBody
	public String loginByCode(@RequestParam("code")String code,HttpSession session){
		String userJson = WechatUtil.getWechatUserByCode(code);
		User user = new User();
		JSONObject jsonObj = JSON.parseObject(userJson);
		user.setAvatarUrl(jsonObj.getString("headimgurl"));
		user.setNick(jsonObj.getString("nickname"));
		user.setOpenid(jsonObj.getString("openid"));
		User u = userService.saveUserIfnotExists(user);
		session.setAttribute(Constant.SESSION_USERINFO, u);
		return new ResponseVO(u).toString();
	}
	
	/**
	 * 通过页面传递回来的opend，获取到用户信息
	 * @param code
	 * @param session
	 * @return
	 */
	@RequestMapping("loginByOpenid")
	@ResponseBody
	public String loginByOpenid(@RequestParam("openid")String openid,HttpSession session){
		User user = userService.getUserByOpenid(openid);
		session.setAttribute(Constant.SESSION_USERINFO, user);
		return new ResponseVO(user).toString();
	}
	
}
